package com.jt.config;

import jdk.nashorn.internal.ir.RuntimeNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.omg.CORBA.Request;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    protected void configure(HttpSecurity http) throws Exception {
        //关闭跨域工具
        http.csrf().disable();
        //放心所有请求
        http.authorizeRequests().anyRequest().permitAll();
        //登录成功与失败的处理
        http.formLogin().successHandler(successHandler())
                .failureHandler(failureHandler());
    }

    @Bean
    public AuthenticationFailureHandler failureHandler() {
        return (requesty,response,e)-> {
            Map<String,Object> map = new HashMap();
            map.put("state",500);
            map.put("message","login failure");
            writeJsonToClient(response,map);
        };
    }


    @Bean
    public AuthenticationSuccessHandler successHandler() {
        return (requesty,response,e)-> {
            Map<String,Object> map = new HashMap();
            map.put("state",200);
            map.put("message","login ok");
            writeJsonToClient(response,map);
        };
    }

    private void writeJsonToClient(HttpServletResponse response,Object object) throws IOException {
        String jsonStr=new ObjectMapper().writeValueAsString(object);
        //3.将json字符串写到客户端
        PrintWriter writer = response.getWriter();
        writer.println(jsonStr);
        writer.flush();

    }
    @Bean
    public AuthenticationManager authenticationManagerBean()
            throws Exception {
        return super.authenticationManagerBean();
    }

}
